package com.example.account;

import static android.content.Intent.getIntent;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.inputmethodservice.KeyboardView;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.account.DataBase.AccountData;
import com.example.account.DataBase.AccountDataBase;
import com.example.account.DataBase.AccountDataDao;
import com.example.account.DataBase.TypeData;
import com.example.account.DataBase.TypeDataDao;
import com.example.account.DataBase.TypeDatabase;

import java.sql.SQLOutput;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import android.content.Intent;

//支出模块
public class InFragment extends Fragment implements View.OnClickListener {
    KeyboardView my;
    EditText et;
    ImageView iv;
    TextView tv_type,tv_bz,tv_time;
    GridView gv;
    private static TypeDatabase typeDatabase;
    private static TypeDataDao typeDataDao;
    private AccountDataBase accountDataBase;
    private AccountDataDao accountDataDao;
    private static List<TypeData>sin=new ArrayList<>();
    private static TypeDataAdapter adapter;
    private AccountData accountData;
    private Intent intent;
    private String model;
    private int lasid;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        typeDatabase=TypeDatabase.getDatabase(getContext());
        typeDataDao= (TypeDataDao) typeDatabase.getDataDao();
        accountDataBase=AccountDataBase.getDatabase(getContext());
        accountDataDao=accountDataBase.getDataDao();
        intent = getActivity().getIntent();
        accountData=new AccountData();
        model=intent.getStringExtra("type");
        System.out.println("取出的type值为"+model);
    }
    private void updateshow() {
        lasid= Integer.parseInt(intent.getStringExtra("id"));
        System.out.println("取出的id值为"+lasid);
        accountData=accountDataDao.FindById(lasid);
        System.out.println(accountData);
        iv.setImageResource(accountData.getImageid());
        tv_type.setText(accountData.getName());
        String bbz=accountData.getBz();
        if(bbz==null) bbz="添加备注";
        tv_bz.setText(bbz);
        tv_time.setText(accountData.getTime());
        String t= String.valueOf(accountData.getMoney());
        et.setText(t);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_out, container, false);
        initviews(view);
        loadGV();
        setGVlinster();
        if(model.equals("update")){
            updateshow();
        }
        else{
            accountData.setName("其他");
            accountData.setImageid(R.mipmap.it_qita);
        }
        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        String nowtime=simpleDateFormat.format(date);
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if(model.equals("add")){
            accountData.setTime(nowtime);
            tv_time.setText(nowtime);
            accountData.setYear(year);
            accountData.setMonth(month);
            accountData.setDay(day);
        }

        return view;
    }

    private void setGVlinster() {
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                adapter.selectPos=i;
                adapter.notifyDataSetInvalidated();
                TypeData ty= sin.get(i);
                tv_type.setText(ty.getName());
                iv.setImageResource(ty.getYi_id());
                accountData.setImageid(ty.getYi_id());
                accountData.setName(ty.getName());
            }
        });
    }

    private void loadGV() {
        sin=typeDataDao.findByKind(-1);
        adapter=new TypeDataAdapter(getContext(),sin);
        gv.setAdapter(adapter);
    }

    private void initviews(View view) {
        my=view.findViewById(R.id.frag_record_jp);
        et=view.findViewById(R.id.frag_record_et);
        iv=view.findViewById(R.id.frag_record_iv);
        tv_type=view.findViewById(R.id.frag_record_type);
        tv_bz=view.findViewById(R.id.frag_record_bz);
        tv_time=view.findViewById(R.id.frag_record_time);
        gv=view.findViewById(R.id.frag_record_gv);
        tv_bz.setOnClickListener(this);
        tv_time.setOnClickListener(this);
        //显示自定义软键盘
        Jianpan jp=new Jianpan(my,et);
        jp.show();
        jp.setOnEnsureListener(new Jianpan.OnEnsureListener() {
            @Override
            public void onEnsure() {
                String nowmoney=et.getText().toString();
                System.out.println(nowmoney+"***********");
                if(TextUtils.isEmpty(nowmoney)||nowmoney.equals("0")) {
                    getActivity().finish();
                    return;
                }
                accountData.setMoney(Float.parseFloat(nowmoney));
                System.out.println(accountData);
                AddData();
                getActivity().finish();
                return ;
            }
        });
    }

    private void AddData() {
        accountData.setType(1);
        if(model.equals("add"))
            accountDataDao.insertAccountData(accountData);
        else accountDataDao.Update(accountData);
    }

    @Override
    public void onClick(View view){
        switch (view.getId()){
            case R.id.frag_record_bz:
                System.out.println("点击了备注");
                ShowBZ();
                break;
            case R.id.frag_record_time:
                System.out.println("点击了时间");
                showTime();
                break;
        }
    }
    String ttime;
    private void showTime() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        View view = View.inflate(getContext(), R.layout.dialog_time, null);
        final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker);
        final TimePicker timePicker = (android.widget.TimePicker) view.findViewById(R.id.time_picker);
        builder.setView(view);

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null);

        timePicker.setIs24HourView(true);
        timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        timePicker.setCurrentMinute(Calendar.MINUTE);
        builder.setPositiveButton("确  定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String CurrentHour=timePicker.getCurrentHour().toString();
                String CurrentMinute=timePicker.getCurrentMinute().toString();

                if (timePicker.getCurrentHour() >= 0 && timePicker.getCurrentHour() <= 9) {
                    CurrentHour = "0" + timePicker.getCurrentHour() ;
                }
                if (timePicker.getCurrentMinute() >= 0 && timePicker.getCurrentMinute() <= 9) {
                    CurrentMinute = "0" + timePicker.getCurrentMinute();
                }
                StringBuffer sb = new StringBuffer();
                sb.append(String.format("%d年%02d月%02d日",
                        datePicker.getYear(),
                        datePicker.getMonth() + 1,
                        datePicker.getDayOfMonth()));
                sb.append("  ");
                sb.append(CurrentHour)
                        .append(":").append(CurrentMinute)
                        .append(":00");

                ttime=sb.toString();
                System.out.println(ttime);
                tv_time.setText(ttime);
                accountData.setYear(datePicker.getYear());
                accountData.setMonth(datePicker.getMonth() + 1);
                accountData.setDay(datePicker.getDayOfMonth());
                accountData.setTime(ttime);
                dialog.cancel();//取消dialog
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }


    private void ShowBZ() {
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(getContext());
        final View dialogView = LayoutInflater.from(getContext())
                .inflate(R.layout.dialog_bz,null);
        customizeDialog.setTitle("请输入备注");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText edit_text =
                                (EditText) dialogView.findViewById(R.id.dialog_et_bz);
                        Toast.makeText(getContext(),
                                edit_text.getText().toString(),
                                Toast.LENGTH_SHORT).show();
                        String bz=edit_text.getText().toString();
                        System.out.println(bz);
                        accountData.setBz(bz);
                        tv_bz.setText(bz);
                    }
                });
        customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        customizeDialog.show();
    }

}